import type { State } from '..';
import http from "@/utils/http";
import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import { ethers } from 'ethers'

interface Infos {
    [index: string]: any
}
interface Wallet {
    [index: string]: any
}
export interface UsersState {
    currentAddress: string;
    isEmailLogin:boolean;
    token: string
    infos: Infos
    wallet: Wallet
}


const state: UsersState = {
    currentAddress: '',
    isEmailLogin:false,
    token: '',
    infos: {},
    wallet: {}
}


const mutations: MutationTree<UsersState> = {
    updateCurrentAddress(state, data) {
        state.currentAddress = data
    },
    updateToken(state, data) {
        state.token = data
    },
    updateIsEmailLogin(state,data){
        state.isEmailLogin = data
    },
    updateInfos(state, data) {
        state.infos = data
    },
    updateInfo(state, data) {
        state.infos = {
            ...state.infos,
            ...data
        }
    },
    updateWallet(state, data) {
        state.wallet = data
    },
    clearToken(state) {
        state.token = ''
        state.infos = {}
        state.wallet = {}
        state.isEmailLogin = false
    }
}

async function getAddress() {
    const provider = new ethers.providers.Web3Provider((window as any).ethereum)
    await provider.send("eth_requestAccounts", []);
    const signer = provider.getSigner()
    const address = await signer.getAddress()
    return address
}

const actions: ActionTree<UsersState, State> = {
    async checkTokenType(_, data) {
        if((_.state.currentAddress !== _.state.infos.address) && !_.state.isEmailLogin){
            _.commit('clearToken')
        }
        
        const ret: any = await http.get('user/user/tourist')
        if (ret.code === 0) {
            if (ret.data === 'success') {
                _.commit('updateInfo', {
                    isLogin: true
                })
            } else {
                _.commit('updateInfo', {
                    isLogin: false
                })
                _.commit('updateToken',ret.data)
            }
        }
    },
    getRechargeInfo(_, data) {
        return http.get('user/user_address/app')
    },
    async signEditAddress(_,data){
        const ret:any = await http.post('user/user/update/address/message',{
            address: _.state.currentAddress
        })
        if(ret.code === 0){
            const provider = new ethers.providers.Web3Provider((window as any).ethereum)
            await provider.send("eth_requestAccounts", []);
            const signer = provider.getSigner()
            const signature = await signer.signMessage(ret.data)
            return signature
        }
    },
    async getCurrentEthAddress(_, data) {
        if ((window as any).ethereum) {
            // const timer = setInterval(async () => {
                const address = await getAddress()
                console.log('获取当前地址', address)
                if (address) {
                    // clearInterval(timer)
                    _.commit('updateCurrentAddress', address)
                    return address
                }
            // }, 500)
        }
    },
    async emailLogin(_, data) {
        const ret: any = await http.post('user/user/email/login', data)
        if (ret.code === 0) {
            _.commit('updateToken', ret.data.accessToken)
            _.commit('updateInfos', ret.data)
            return true
        }
    },
    async getUserWalletInfo(_, data) {
        const ret: any = await http.get('user/user/wallet')
        if (ret.code === 0) {
            _.commit('updateWallet', ret.data)
            return true
        }
    },
    sendEmailCodeL(_, data) {
        return http.post('user/user/email/l', data)
    },
    sendEmailCode(_, data) {
        return http.post('user/user/email', data)
    },
    async updateUserInfo(_, data) {
        const ret: any = await http.get('user/user/app/detail', {
            id: '-1'
        })
        if (ret.code === 0) {
            _.commit('updateInfos', ret.data)
        }
    },
    async register(_, data) {
        const ret: any = await http.post('user/user/registered', data)
        if (ret.code === 0) {
            _.dispatch('updateUserInfo')
            return true
        }
    },
    async getSignMessage(_, data) {
        return new Promise((resolve, reject) => {
            const address = _.state.currentAddress
            http.post('user/user/getAddressMassage', {
                address
            }).then(async (ret: any) => {
                if (ret.code === 0) {
                    setTimeout(async () => {
                        const provider = new ethers.providers.Web3Provider((window as any).ethereum)
                        await provider.send("eth_requestAccounts", []);
                        const signer = provider.getSigner()
                        const signature = await signer.signMessage(ret.data)
                        const ret2: any = await http.post('user/user/login', {
                            address,
                            chain: 'eth',
                            signature,
                        })
                        if (ret2.code === 0) {
                            _.commit('updateToken', ret2.data.accessToken)
                            _.commit('updateInfos', ret2.data)
                            resolve(true)
                        } else {
                            resolve(false)
                        }
                    }, 200)
                } else {
                    resolve(false)
                }
            })
        })
    },
}

const getters: GetterTree<UsersState, State> = {

}


export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}